import * as fse from "fs-extra";
import * as express from "express";

import { getMP3 } from "../db/media";
import { debug } from "../utils/log";
import { normalizeQuery } from "./query";
import { resolveFile } from "../utils/fs";
import { Message } from "../utils/message";

export async function routerAudioDecode(
	req: express.Request,
	res: express.Response
) {
	const normalQuery = normalizeQuery(req.query);

	debug({
		url: "/decode",
		query: normalQuery,
	});

	const media = await getMP3(normalQuery);

	// 数据库中不存在
	if (media.length === 0) {
		return res.send(
			Message.err("AUDIO_NOT_FOUND", 404, {
				info: "AUDIO_NOT_FOUND",
			})
		);
	}

	try {
		const virtualPath = media[0].virtualPath;
		const filePath = resolveFile(virtualPath);
		const stat = fse.statSync(filePath);

		res.writeHead(200, {
			"Content-Type": "audio/mp3",
			"Content-Length": stat.size,
			"Accept-Ranges": "bytes",
		});
		const readStream = fse.createReadStream(filePath);
		readStream.pipe(res);
	} catch (err) {
		return res.send(
			Message.err("AUDIO_NOT_FOUND", 404, {
				info: "AUDIO_NOT_FOUND",
			})
		);
	}
}

export async function routerVideoDecode(
	req: express.Request,
	res: express.Response
) {
	const normalQuery = normalizeQuery(req.query);

	debug({
		url: "/decode",
		query: normalQuery,
	});

	const media = await getMP3(normalQuery);

	// 数据库中不存在
	if (media.length === 0) {
		return res.send(
			Message.err("VIDEO_NOT_FOUND", 404, {
				info: "VIDEO_NOT_FOUND",
			})
		);
	}
	const virtualPath = media[0].virtualPath;
	const filePath = resolveFile(virtualPath);

	// 文件目录中不存在
	const stat = fse.statSync(filePath);
	if (!stat.isFile) {
		return res.send(
			Message.err("VIDEO_NOT_FOUND", 404, {
				info: "VIDEO_NOT_FOUND",
			})
		);
	}

	res.writeHead(200, {
		"Content-Type": "video/mp4",
		"Content-Length": stat.size,
		"Accept-Ranges": "bytes",
	});
	const readStream = fse.createReadStream(filePath);
	readStream.pipe(res);
}
